  // pages/order/order.js
  const app = getApp()
  import Api from '../../utils/api';
  import util from '../../utils/util';
  var searchBillInterval;
  Page({

    /**
     * 页面的初始数据
     */
    data: {
      array: ['快递', '到店自提', '壹配送', '到店消费'],
      deliveryType: ['POST', "ZT", 'YPS', 'CONSUME'],
      indexType: 0, //获取可选配送方式的索引
      index: 0,
      isCartPay: false, // 是否从购物车进来的
      goodsId: "", //商品id
      shopId: '', //店铺id
      cartItemDtoList: [], //购物车列表
      shopInfo: {}, //店铺信息
      remarks: "", //备注 
      num: 1,
      totalNum: 1, //商品总数量
      couponId: "", //红包id
      couponText: '', //红包标题
      addressId: '', //地址id
      isGetAddress: false, //是否有地址信息
      formId: "", //表单id
      ordinaryInfo: {}, //预览信息
      storeCount: 0, //库存
      //city: '', //店铺的城市
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
      let _this = this;
      console.log(options)
      //options.id = "1153922138810486784";
      //options.shopId = "1146268760156540928";
      if (options.id != undefined) { //普通订单 
        _this.setData({
          goodsId: options.id,
          shopId: options.shopId,
        })
        _this.getGoodsDetailInfo();
        //_this.getShopInfo();
      } else { //购物车
        _this.setData({
          shopId: options.shopId,
          isCartPay: true,
          cartItemDtoList: wx.getStorageSync("cartItemDtoList"),
        })
      }
      _this.getShopInfo(function() {
        _this.getAddress();
      });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
      let _this = this;
      if (_this.data.shopInfo) {
        _this.getAddress();
      }

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
      app.globalData.otherPageHideFlag = true;
    },
    // 配送方式选择
    bindPickerChange: function(e) {
      //console.log(e)
      let _this = this;
      var type = _this.data.array[e.detail.value];
      _this.setData({
        indexType: e.detail.value,
      })
      //console.log(_this.data.indexType)
      _this.ordinaryOrderInfo();
    },

    //获取默认地址
    getAddress(callback) {
      let _this = this;
      if (_this.data.addressId == '') {
        Api.getDefaultAddress().then(res => {
          console.log(res)
          if (res.data) {
            _this.setData({
              userAddress: res.data,
              isGetAddress: true,
              addressId: res.data.id
            });
          }
          _this.isEqualCity();
          //(callback && typeof (callback) === "function") && callback();
        })
      } else {
        Api.queryAddressId(_this.data.addressId).then(res => {
          //console.log(res)
          _this.setData({
            userAddress: res.data,
            isGetAddress: true,
            // addressId: res.data.id
          });
          _this.isEqualCity();
          // (callback && typeof (callback) === "function") && callback();
        })
      }
    },

    //判断当前城市和收货地址城市是否一致
    isEqualCity() {
      let _this = this;
      let shopCity = new RegExp(_this.data.shopInfo.city);
      if (_this.data.userAddress && shopCity.test(_this.data.userAddress.city)) {
        _this.setData({
          array: ['快递','到店自提',  '壹配送', '到店消费'],
          deliveryType: ['POST',"ZT",'YPS', 'CONSUME'],
          indexType: 0,
        })
      } else {
        _this.setData({
          array: ['快递','到店自提', '到店消费'],
          deliveryType: ['POST',"ZT",  'CONSUME'],
          indexType: 0,
        })
      }

      _this.ordinaryOrderInfo()
    },


    //预览订单信息
    ordinaryOrderInfo() {
      let _this = this;
      console.log(_this.data.cartItemDtoList[0])
      let data = {
        "addressId": _this.data.addressId,
        "couponId": _this.data.couponId,
        "shopId": _this.data.shopId,
        "deliveryType": _this.data.deliveryType[_this.data.indexType],
        "isCartPay": _this.data.isCartPay,
        "payType": "WX_JSAPI",
        "paymentToType": "PAY_MCH",
        "goodsId": _this.data.goodsId,
        "num": _this.data.cartItemDtoList[0] ? _this.data.cartItemDtoList[0].num:1,
        "cartItemDtoList": _this.data.cartItemDtoList,
      }
      console.log(data)
      Api.ordinaryOrderInfo(data).then(res => {
        console.log("预览订单信息", res);
        if (_this.data.isCartPay) {
          //购物车添加
          if (_this.data.cartItemDtoList && _this.data.cartItemDtoList.length > 0) {
            let arr = _this.data.cartItemDtoList;
            var totalNum = 0;
            arr.forEach(function(item, index, arr) {
              totalNum += item.num;
            })
            _this.setData({
              totalNum: totalNum
            })
          }
        } else {
          //普通添加
          _this.setData({
            totalNum: _this.data.cartItemDtoList[0].num
          })
        }
        _this.setData({
          ordinaryInfo: res.data
        })
      });
    },



    //创建订单
    createOrder() {
      let _this = this;
      let data = {
        "addressId": _this.data.addressId, //地址id
        "couponId": _this.data.couponId, //红包ID
        "shopId": _this.data.shopId, //店铺ID
        "deliveryType": _this.data.deliveryType[_this.data.indexType], //配送方式  ['到店自提',  '壹配送'],["ZT", 'POST', 'YPS'],
        "isCartPay": _this.data.isCartPay, //是否购物车支付
        "payType": "WX_JSAPI", //支付方式  
        "paymentToType": "PAY_TOP", //支付到平台方式，这个看黄超对接情况 PAY_MCH,//支付至商户  PAY_TOP,//支付至平台
        "goodsId": _this.data.goodsId, //商品ID
        "num": _this.data.cartItemDtoList[0].num, //数量
        "cartItemDtoList": _this.data.cartItemDtoList, //购物车列表
        "remarks": _this.data.remarks, //备注 
        "formId": _this.data.formId, //表单ID
      }
      //console.log(data)
      Api.createOrder(data).then(res => {
        console.log("创建订单", res)
        //获取支付字符串
        let payString = JSON.parse(res.data.bill.payString);
        let billId = res.data.bill.billId;
        //console.log(typeof payString)
        wx.requestPayment({
          timeStamp: payString.timeStamp,
          nonceStr: payString.nonceStr,
          package: payString.package,
          signType: payString.signType,
          paySign: payString.paySign,
          success(res) {
            wx.showLoading({
              title: '订单创建中',
            })
            //轮询查询支付状态
            searchBillInterval = setInterval(() => {
              Api.queryBillPayStatus(billId).then(response => {
                console.log('账单查询轮询中...', response)
                if (response.data) {
                  wx.hideLoading()
                  if (searchBillInterval) {
                    console.log('账单支付轮询已关闭');
                    clearInterval(searchBillInterval);
                  }
                  wx.redirectTo({
                    url: '/pages/seeOrder/seeOrder?orderStatusIndex=2',
                  })
                }
              });
            }, "1000")
          },
          fail(res) {
            //console.log(res)
            wx.showLoading({
              title: '订单取消中',
            })
            setTimeout(function() {
              wx.hideLoading()
              wx.redirectTo({
                url: '/pages/seeOrder/seeOrder?orderStatusIndex=1',
              })
            }, 2000)

          },
          complete(res) {
            console.log('order.js====调用了微信支付页面complete')
            app.globalData.otherPageHideFlag = true;
          }
        })
      })
    },

    //提交订单
    submitInfo(e) {
      let _this = this;
      console.log(e.detail.formId);
      _this.setData({
        formId: e.detail.formId
      });
      if (!_this.data.addressId && (_this.data.deliveryType[_this.data.indexType] == 'POST' || _this.data.deliveryType[_this.data.indexType] == 'YPS')) {
        wx.showToast({
          title: '请选择收件地址',
          icon: 'none'
        })
        return
      }
      _this.createOrder();
    },

    //获取商品信息
    getGoodsDetailInfo() {
      let _this = this;
      Api.getGoodsDetailInfo(_this.data.goodsId).then(res => {
        console.log("获取商品信息", res);
        let arr = [];
        arr.push(res.data)
        arr[0].num = 1;
        _this.setData({
          cartItemDtoList: arr,
          //city: res.data.city,
        })
        //console.log("获取商品信息", arr);
      })
    },
    //获取店铺信息
    getShopInfo(callback) {
      let _this = this;
      Api.getShopInfo(_this.data.shopId).then(res => {
        console.log("获取店铺信息", res)
        _this.setData({
          shopInfo: res.data.shop
        });
        (callback && (callback) === "function") && callback();
      })
    },

    //减法
    reduceClick(e) {
      let _this = this;
      let index = e.currentTarget.dataset.index;
      let arr = _this.data.cartItemDtoList;
      if (arr[index].num <= 1) {
        arr[index].num = 1
        return;
      }
      arr[index].num--;
      arr[index].totalPrice = arr[index].num * arr[index].price;
      _this.setData({
        cartItemDtoList: arr
      })
      _this.ordinaryOrderInfo();
      //console.log("减法", _this.data.cartItemDtoList[index].num)
    },


    //加法
    addClick(e) {
      let _this = this;
      let index = e.currentTarget.dataset.index;
      let arr = _this.data.cartItemDtoList;
      _this.setData({
        goodsId: arr[index].id
      })
      _this.queryGoodsNum(function() {
        if (arr[index].num < _this.data.storeCount) {
          arr[index].num++;
          arr[index].totalPrice = arr[index].num * arr[index].price;
          _this.setData({
            cartItemDtoList: arr
          })
          _this.ordinaryOrderInfo();
        } else {
          wx.showToast({
            title: '超出现有库存',
            icon: 'loading',
            duration: 2000
          })
        }
      });


      //console.log("加法", _this.data.cartItemDtoList[index].num)
    },

    //获取备注信息
    remarksClick(e) {
      let _this = this;
      _this.setData({
        remarks: e.detail.value
      })
      //console.log(_this.data.remarks)
    },

    //订单商品数量查询
    queryGoodsNum(callback) {
      let _this = this;
      let data = {
        "isShopCart": _this.data.isCartPay, //是否购物车支付
        "goodsId": _this.data.goodsId, //商品ID
        "shopId": _this.data.shopId, //店铺ID
        "num": _this.data.cartItemDtoList[0].num, //数量
        "cartItems": _this.data.cartItemDtoList, //购物车列表
      }
      console.log(data)
      Api.queryGoodsNum(data).then(res => {
        console.log('ssssssss', res)
        _this.setData({
          storeCount: res.data.orderItems[0].storeCount
        });
        (callback && (typeof callback) === "function") && callback();
      })
    },


  })